package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.constant.ScheduleConstants;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.mapper.SysJobMapper;
import com.ruoyi.quartz.util.ScheduleUtils;
import com.ruoyi.system.domain.enums.JobGroupEnum;
import com.ruoyi.system.domain.equipment.EquipmentService;
import com.ruoyi.system.domain.equipment.EquipmentServiceDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.system.mapper.EquipmentServiceMapper;
import com.ruoyi.system.service.IEquipmentServiceService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 设备保养项目Service业务层处理
 *
 * @author ruoyi
 * @date 2023-04-13
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class EquipmentServiceServiceImpl extends ServiceImpl<EquipmentServiceMapper, EquipmentService> implements IEquipmentServiceService {

    private final SysJobMapper jobMapper;
    private final Scheduler scheduler;
    private final TransactionTemplate transactionTemplate;
    @Override
    public boolean insertWithSchedule(EquipmentServiceDTO dto) {
        //新增保养项目
        EquipmentService equipmentService = new EquipmentService();
        BeanUtil.copyProperties(dto,equipmentService);
        String eq = dto.getEquipment().stream().map(String::valueOf).collect(Collectors.joining(","));
        equipmentService.setEquipment(eq);
        String type = dto.getEquipmentType().stream().map(String::valueOf).collect(Collectors.joining(","));
        equipmentService.setEquipmentType(type);
        baseMapper.insert(equipmentService);
        //新增定时任务
        SysJob job = new SysJob();
        job.setJobName(dto.getItemName());
        job.setJobGroup(JobGroupEnum.BAO_YANG.getName());
        job.setInvokeTarget("taskServiceImpl.genEquipmentBy("+equipmentService.getById()+"L)");
        job.setCronExpression(dto.getKeepPeriod());
        job.setConcurrent("1");
        job.setCreateBy(SecurityUtils.getUsername());
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        int rows = jobMapper.insertJob(job);
        if (rows > 0) {
            try {
                ScheduleUtils.createScheduleJob(scheduler, job);
            } catch (Exception e) {
                log.error("创建定时任务失败",e);
                return false;
            }
        }
        return true;
    }

    @Override
    public int removeWithSchedule(List<Long> idList) {
        removeByIds(idList);
        //删除定时任务
        List<String> invokeTargetList = idList.stream()
                .map(id -> "taskServiceImpl.genEquipmentBy(" + id + "L)")
                .collect(Collectors.toList());
        List<SysJob> sysJobList=jobMapper.selectJobListByInvokeTarget(invokeTargetList);

        for (SysJob sysJob : sysJobList) {
            transactionTemplate.execute((status)->{
                try {
                    int rows = jobMapper.deleteJobById(sysJob.getJobId());
                    if (rows > 0) {
                        scheduler.deleteJob(ScheduleUtils.getJobKey(sysJob.getJobId(), sysJob.getJobGroup()));
                    }
                } catch (Exception e) {
                    log.error("删除任务失败",e);
                    status.setRollbackOnly();
                }
                return null;
            });

        }
        return 1;
    }

}
